// OptionsDlg.cpp : implementation of the COptionsDlg class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "sdk-miranda/m_database.h"
#include "resource.h"
#include "Version.h"
#include "GeoMiranda.h"

extern CMirandaPlugin s_plugin;

static bool s_bPasswordChanged = false;

static INT_PTR CALLBACK
DlgProcOptions
	( IN HWND hwndDlg
	, IN UINT msg
	, IN WPARAM wParam
	, IN LPARAM lParam
	)
{
	switch (msg)
	{
	case WM_INITDIALOG:
		{
			DBVARIANT dbv = {0};
			TranslateDialogDefault(hwndDlg);

			CheckDlgButton(hwndDlg, IDC_ENABLE_GEO_STATUS,
				DBGetContactSettingByte(NULL, VERSION_PRODUCTNAME, "EnableStatus", TRUE));

			if (0 == DBGetContactSettingTString(NULL, VERSION_PRODUCTNAME, "Login", &dbv))
			{
				SetDlgItemText(hwndDlg, IDC_EDIT_NAME, dbv.ptszVal);
				SetDlgItemText(hwndDlg, IDC_EDIT_PASSWORD, _T("******"));
				DBFreeVariant(&dbv);
			}

			ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);
			EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE);
			ShowWindow(GetDlgItem(hwndDlg, IDCANCEL), SW_HIDE);
			EnableWindow(GetDlgItem(hwndDlg, IDCANCEL), FALSE);

			s_bPasswordChanged = false;
		}
		return TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDC_REGISTER)
		{
			CallService(MS_UTILS_OPENURL, 1, (LPARAM)"http://www.wi2geo.ru/user/reg/");
			break;
		}

		if ((LOWORD(wParam) == IDC_ENABLE_GEO_STATUS || EN_CHANGE == HIWORD(wParam))
			&& (HWND)lParam == GetFocus())
		{
			if (LOWORD(wParam) == IDC_EDIT_PASSWORD)
				s_bPasswordChanged = true;

			SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
		}
		break;

	case WM_NOTIFY:
		{
			TCHAR szText[64];

			if (PSN_APPLY == ((LPNMHDR)lParam)->code)
			{
				DBWriteContactSettingByte(NULL, VERSION_PRODUCTNAME, "EnableStatus",
					IsDlgButtonChecked(hwndDlg, IDC_ENABLE_GEO_STATUS));

				if (GetDlgItemText(hwndDlg, IDC_EDIT_NAME, szText, ARRAYSIZE(szText)))
					DBWriteContactSettingTString(NULL, VERSION_PRODUCTNAME, "Login", szText);

				if (s_bPasswordChanged && GetDlgItemText(hwndDlg, IDC_EDIT_PASSWORD, szText, ARRAYSIZE(szText)))
				{
					DBWriteContactSettingString(NULL, VERSION_PRODUCTNAME, "PasswordHash", 
						MD5Hash((LPCSTR)ATL::CT2AEX<64>(szText, CP_UTF8)).c_str());
				}

				s_plugin.Login();
			}
		}
		break;
	}

	return FALSE;
}

int
OptInit(WPARAM wParam, LPARAM /*lParam*/)
{
	OPTIONSDIALOGPAGE odp;

	ZeroMemory(&odp, sizeof(odp));
	odp.cbSize = sizeof(odp);
	odp.position = 0;
	odp.hInstance = WTL::ModuleHelper::GetResourceInstance();
	odp.flags = ODPF_BOLDGROUPS;
	odp.pszGroup = LPGEN("Customize");
	odp.pszTitle = LPGEN("Wi2Geo");

	odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS);
	odp.pfnDlgProc = DlgProcOptions;
	CallService(MS_OPT_ADDPAGE, wParam, (LPARAM) &odp);

	return 0;
}

